package com.example.guli.service.oss.controller.admin;

import com.example.guli.common.base.result.R;
import com.example.guli.common.base.result.ResultCodeEnum;
import com.example.guli.service.oss.service.FileService;
import com.example.guli.service.base.exception.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;


/**
 * @创建人 shunxuan
 * 创建时间 2020/7/18
 * @描述
 **/
@Api(description = "阿里云文件管理")
@CrossOrigin
@RestController
@RequestMapping("/admin/oss/file")
@Slf4j
public class FileController {
    @Autowired
    private FileService fileService;//注入接口

    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R upload(
            @ApiParam(value = "文件",required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "模块",required = true) @RequestParam("module") String module)
    {

        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.upload(inputStream, module, originalFilename);
            return R.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (Exception e) {
            //e.printStackTrace();
//            log.error(ExceptionUtils.getMessage(e));
            //抛出自定义异常
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @ApiOperation("文件删除")
    @PostMapping("remove")
    public R removeFile(@ApiParam(value = "要删除的文件路径",required = true) @RequestBody String url){
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }

    @ApiOperation("测试oss服务调用-服务的生产者")
    @PostMapping("test")
    public R test(){
//        log.info("oss test被调用");
//        return R.ok();

        log.info("oss test被调用");
        try {
            //模拟长流程业务，即讲师删除了而讲师头像没有删除的情况，延迟3秒
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return R.ok();
    }
}
